// pages/search/search.js
const utils = require('../../utils/util.js')
const gd = getApp().globalData;
const getStorage = utils.wxPromisify(wx.getStorage)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domain:gd.domain,
    mapjson:'',
    exhibitions:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const area = wx.getStorageSync('area')
    //设置标题栏
    wx.setNavigationBarTitle({
      title: area.museum_name,
    })
    //获取本地存储的映射文件
    getStorage({
      key:'mapjson'
    }).then(res => {
      //temp.splice(0,1)//截取掉博物馆默认的第一条数据（不存在了）
      this.setData({
        mapjson:res.data,
        museum:area.museum
      })
    },err => {
      wx.showToast({
        title: '网络请求失败',
        icon:'none',
        duration:1000
      })
    })
  },
  /**
   * 检测输入以及搜索
   */
  inputTyping: function (e) {
    let value = e.detail.value
    if (value == '') return //|| value.length < 2
    wx.showLoading({
      title: '加载中'
    })
    let key = e.detail.value
    //查询匹配结果
    const result = utils.findforRegExp(this.data.mapjson, 'exhibit_name', value)
    //获取匹配结果的高亮数组
    let newExhibitions = result.map((item) => {
      return {
        ...item,
        searchArray: this.getHilightStrArray(item.exhibit_name, key),
        keyName: key
      }
    })
    this.setData({
      inputVal: e.detail.value,
      exhibitions: newExhibitions,
    })
    const hideNum = setInterval(() => {
      wx.hideLoading()
      clearInterval(hideNum)
    },1000)
    
  },
  //隐藏输入框
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  //清除输入
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },

  //分割字符串函数
  getHilightStrArray: function (str, key) {
    return str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
  }


})